
using IWshRuntimeLibrary;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Net;
using System.Numerics;
using System.Text;
namespace 考试监视器
{
    public partial class Form1 : Form
    {

        private static string xiaohei_path = "";
        private static string kaoshi_dir = "";
        private FolderMonitor monitor;
        private string file_name;
        private bool issub = false;
        BrowserLauncher browserLauncher;
        public Form1()
        {
            InitializeComponent();

            kaoshi_dir = Get_Monitor_Dir();

            if (kaoshi_dir.Equals(""))
            {
                MessageBox.Show("没有选择小黑课堂 程序结束");
                Environment.Exit(0);
            }
            monitor = new FolderMonitor();

        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                if (Get_Process("小黑课堂计算机题库"))
                {
                    MessageBox.Show("小黑课堂正在运行，请关闭小黑课堂，先点击开始考试再打开小黑课堂");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message);
            }


            try
            {
                string name = textBox1.Text;
                string num = textBox2.Text;
                string time = Get_time();
                textBox1.Enabled = false;
                textBox2.Enabled = false;


                file_name = name + "_" + num + "_" + time + ".txt";
                file_name = file_name.Replace(" ", "_").Replace(":", "_");
                monitor.StartMonitoring(kaoshi_dir, name + "   " + num + "  " + time);
                button1.Enabled = false;
                button1.Text = "考试中";
                button2.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误，请呼叫管理员帮忙解决问题：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        private bool Get_Process(string name)
        {
            string processName = name; // 进程名，不需要.exe后缀  

            // 获取所有运行的进程  
            Process[] processes = Process.GetProcessesByName(processName);

            // 判断是否存在指定进程  
            if (processes.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //获取网络时间和本地时间
        private string Get_time()
        {
            // 尝试获取网络时间  
            try
            {
                // 创建一个 WebClient 实例  
                using (WebClient client = new WebClient())
                {
                    // 下载一个时间同步服务的网页，例如 Google 的时间服务  
                    string timeData = client.DownloadString("http://baidu.com");

                    // 在此处解析网页内容以获取准确的时间信息  
                    // 这可能因所选时间服务的不同而有所差异  
                    // 解析时间数据...  

                    // 假设你已经成功解析了时间数据，将其转换为 DateTime 对象  
                    DateTime networkTime = DateTime.Parse(timeData);

                    // 将网络时间格式化为字符串  
                    string formattedNetworkTime = networkTime.ToString("yyyy-MM-dd HH:mm:ss");

                    return formattedNetworkTime;
                }
            }
            catch (Exception)
            {
                // 如果获取网络时间失败，则返回本地时间  
                DateTime localTime = DateTime.Now;
                string formattedLocalTime = localTime.ToString("yyyy-MM-dd HH:mm:ss");
                return formattedLocalTime;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            // 指定当前文件的完整路径
            button2.Text = "正在提交请勿操作";
            button2.Enabled = false;

            using (WebClient client = new WebClient())
            {
                try
                {
                    string currentFilePath = @"sdasdasd.txt";

                    DecodeFileAndSave(currentFilePath, file_name);
                    string webDavUrl = "你的webdav链接" + file_name;
                    string sourceFilePath = file_name;
                    string username = "你的webdav账号";
                    string password = "密码";
                    // 设置WebDAV认证信息
                    client.Credentials = new NetworkCredential(username, password);
                    // 上传文件
                    client.UploadFile(webDavUrl, "PUT", sourceFilePath);
                    MessageBox.Show("文件上传成功，现在你可以关闭程序了", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    System.IO.File.Delete(file_name);
                    button2.Text = "可以关闭程序了";
                    ReturnEncryptDocuments();
                    issub = true;

                }
                catch (Exception ex)
                {
                    MessageBox.Show("文件上传失败，原因是" + ex.Message + "！！！！将开始把加密日志移植到桌面，请你向老师举手", "失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    using (PasswordForm passwordForm = new PasswordForm())
                    {
                        if (passwordForm.ShowDialog() == DialogResult.OK)
                        {

                            ReturnEncryptDocuments();

                        }
                    }

                    button2.Enabled = true;
                    button2.Text = "考试结束--提交日志";

                }

            }





        }

        private void ReturnEncryptDocuments()
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            string sourceFilePath = Path.Combine(currentDirectory, "sdasdasd.txt");
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string destinationFilePath = Path.Combine(desktopPath, file_name);

            if (System.IO.File.Exists(sourceFilePath))
            {
                System.IO.File.Copy(sourceFilePath, destinationFilePath, true); // 第三个参数表示如果目标文件已存在，则覆盖它  
                MessageBox.Show("加密后的文件已成功移动到桌面！");
                issub = true;
            }
            else
            {
                MessageBox.Show("源文件不存在,文件未能成功移动到本地！，请你向老师举手");
            }
        }

        static void DecodeFileAndSave(string sourceFilename, string newFilename)
        {
            // 确保源文件存在
            if (!System.IO.File.Exists(sourceFilename))
            {
                Console.WriteLine("Source file does not exist.");
                return;
            }

            // 读取源文件的所有行
            string[] encodedLines = System.IO.File.ReadAllLines(sourceFilename);
            string[] decodedLines = new string[encodedLines.Length];

            // 解码每一行
            for (int i = 0; i < encodedLines.Length; i++)
            {
                decodedLines[i] = BinaryPlusOneToString(encodedLines[i]);
            }
            Console.WriteLine(decodedLines);
            // 将解码后的内容写入新文件
            System.IO.File.WriteAllLines(newFilename, decodedLines);

        }

        static string BinaryPlusOneToString(string binaryStringPlusOne)
        {
            // 将二进制字符串转换为BigInteger，减一
            BigInteger binaryValue = BigInteger.Parse(binaryStringPlusOne, System.Globalization.NumberStyles.HexNumber);
            binaryValue -= 12314;

            // 将BigInteger转换回字节数组
            byte[] bytes = binaryValue.ToByteArray().Reverse().ToArray();

            // 将字节数组转换回字符串
            string decodedString = Encoding.UTF8.GetString(bytes);
            return decodedString;
        }
        private string Get_Monitor_Dir()
        {
            browserLauncher = new BrowserLauncher();
            xiaohei_path = getpath();
            if (xiaohei_path.Equals("错误") || xiaohei_path == null)
            {
                //弹出窗口手动赋值
                // 弹出窗口手动选择文件夹目录  
                MessageBox.Show("你可能安装了假的小黑课堂！！请呼叫老师过来检查！");
                using (PasswordForm passwordForm = new PasswordForm())
                {
                    if (passwordForm.ShowDialog() == DialogResult.OK)
                    {
                        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                        DialogResult result = folderBrowserDialog.ShowDialog();

                        if (result == DialogResult.OK)
                        {
                            kaoshi_dir = folderBrowserDialog.SelectedPath;


                        }
                        else
                        {
                            kaoshi_dir = "";
                        }
                    }
                    else
                    {
                        kaoshi_dir = "";
                    }
                }

            }
            else
            {
                //获取考试文件夹
                kaoshi_dir = xiaohei_path + "\\xhkt\\ms650000001";
                if (!Directory.Exists(kaoshi_dir))
                {
                    // 如果不存在 kaoshi_dir 这个目录则创建  
                    Directory.CreateDirectory(kaoshi_dir);
                }
            }
            return kaoshi_dir;
        }


        private string getpath()
        {
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string shortcutPath = System.IO.Path.Combine(desktopPath, "小黑课堂计算机二级Office题库.lnk");

            if (System.IO.File.Exists(shortcutPath))
            {
                WshShell shell = new WshShell();
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
                string directoryPath = Path.GetDirectoryName(shortcut.TargetPath);
                return directoryPath;
            }
            else
            {
                return "错误";
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (issub == false)
            {
                MessageBox.Show("禁止退出！请提交文件后退出");
                e.Cancel = true;
            }
            else
            {
                Application.Exit();
            }


        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {
            MessageBox.Show(kaoshi_dir + " " + monitor.status);
        }
    }

}